package com.ying.common.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ying.common.exception.BaseException;

/**
 * Created by xingwang on 2017/8/1.
 * 返回值封装
 */
public class Response<T> {

    private static final String OK = "ok";
    private static final String ERROR = "error";
    private static final Integer CODE_OK = 0;
    private static final Integer CODE_ERROR = -1;
    private Integer code;
    private String msg;
    private T data;
    @JsonIgnore
    private Object obj;

    public Response success() {
        this.code = CODE_OK;
        this.msg = OK;
        return this;
    }

    public Response success(T data) {
        this.code = CODE_OK;
        this.msg = OK;
        this.data = data;
        return this;
    }

    /**
     * 用户自定义
     */
    public Response userDefined(Integer code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
        return this;
    }

    /**
     * 用户登录自定义
     */
    public Response userLoginDefined(ResponseCode responseCode){
        this.code = responseCode.getCode();
        this.msg = responseCode.getMsg();
        return this;
    }

    public Response userLoginDefined(ResponseCode responseCode, T data){
        this.code = responseCode.getCode();
        this.msg = responseCode.getMsg();
        this.data = data;
        return this;
    }

    public Response failure() {
        this.code = CODE_ERROR;
        this.msg = ERROR;
        return this;
    }

    public Response failure(String msg) {
        this.code = CODE_ERROR;
        this.msg = msg;
        return this;
    }

    private Response exception(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.obj = data;
        return this;
    }

    public <T extends BaseException> Response exception(T t) {
        return exception(t.getCode(), t.getMsg(), t.getData());
    }

    public Response() {
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }
}
